package com.niit.controller;

import com.niit.pojo.Unit;
import com.niit.service.UnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Controller

public class UnitController {

    @Autowired
    private UnitService unitService;

    @GetMapping("/getAllUnit")
    @ResponseBody
    public List<Unit> list() {
        List<Unit> unit = unitService.getAllUnits();
        return unit;
    }

    @RequestMapping("/unit")
    public String unit_table() {
        return "unit";
    }
    @RequestMapping("/toAddUnit")
    public String toAddUnit() {
        return "/addUnit";
    }
    @PostMapping("/addUnit")
    public String addUnit(Unit unit) {
        unitService.addUnit(unit);
        return "redirect:/toAddProduct";
    }


    @PostMapping("/editUnit")
    @ResponseBody
    public String updateGame(@RequestBody Unit unit){
        unitService.updateUnit(unit);
        return "更改成功!";
    }
    @PostMapping("/deleteUnit")
    @ResponseBody
    public ResponseEntity<String> deleteGame(@RequestBody Map<String,String> requestData){
        int unit_id= Integer.parseInt(requestData.get("unit_id"));
        try {
            unitService.deleteUnit(unit_id);
            return  ResponseEntity.ok("删除成功!");

        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("删除失败");
        }

    }
}